<template>
  <div class="alarm">
    <div class="tools">
      <el-select v-model="search.alarmSource" placeholder="请选择报警来源" size="large" clearable
        @change="getAlarmTypeDictFun">
        <el-option v-for="item in alarmSourceList" multiple :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <el-select v-model="search.alarmType" placeholder="请选择报警类型" size="large" clearable>
        <el-option v-for="item in alarmTypeList" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
    </div>
    <div class="alarm-list" v-infinite-scroll="scrollLoad" :infinite-scroll-distance="50"
      :infinite-scroll-immediate="false">
      <template v-for="item in listData" :key="item.alarmId">
        <div class="alarm-item" :class="{ notRead: item.isRead === '0' }" @click="handleAlarmItem(item)">
          <el-icon class="alarm-item-track" @click.stop="goBackTrack(item)"><Clock /></el-icon>
          <div class="alarm-item-alarm-type">
            <div>
              <span class="alarm-item-alarm-type-text">
                {{item.alarmTypeName}}
              </span>
              <span>&nbsp;&nbsp;·&nbsp;&nbsp;</span>
              <span>{{ getAlarmSource(item.alarmSource) }}</span>
            </div>
          </div>
          <div class="alarm-item-content">
            <span>{{ item.content }}</span>
          </div>
          <div class="alarm-item-time-duration">
            <span>{{ item.beginTime }}</span>
            <span>{{ item.keepTimeStr2 }}</span>
          </div>
        </div>
      </template>
      <div v-if="baseSearch.status" class="status">
        {{ baseSearch.status }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getAlarmSourceDict, getAlarmTypeDict } from '@/api/dict'
import { getAlarmList } from '@/api/alarm'
import JcjkAlarmDetail from './jcjkAlarmDetail/index.vue'
import { $bDialog } from '@/components/b-dialog'
import { useListData } from '@/hooks/useListData'
import { Clock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/store/auth'
import dayjs from 'dayjs'
import { useDialog } from '@/hooks/useDialog'
// 定义组件名称
defineOptions({
  name: 'AlarmView'
})

// 定义字典项接口
interface DictItem {
  id: string
  label: string
}

// 定义报警项接口
interface AlarmItem {
  alarmId: string
  alarmSource: string       // 报警来源
  alarmTypeName: string     // 报警类型名称
  content: string           // 报警内容
  beginTime: string         // 开始时间
  keepTimeStr2: string      // 持续时间
  isRead: string            // 是否已读（0-未读，1-已读）
  areaName: string          // 区域名称
  [key: string]: any        // 其他属性
}

// 定义搜索参数接口
interface SearchParams {
  alarmSource: string
  alarmType: string
}

// 报警来源列表
const alarmSourceList = ref<DictItem[]>([])
// 报警类型列表
const alarmTypeList = ref<DictItem[]>([])

/**
 * 使用列表数据钩子，管理报警列表数据
 */
const { search, baseSearch, listData, scrollLoad } = useListData<SearchParams>({
  // 获取报警列表数据的函数
  fetchData: getAlarmList,
  // 初始搜索参数
  initialSearchParams: {
    alarmSource: '',
    alarmType: ''
  },
  // 启用自动刷新
  enableAutoRefresh: true,
  // 刷新间隔时间（1分钟）
  refreshInterval: 60000
})

/**
 * 组件挂载时获取报警来源字典
 */
onMounted(async () => {
  // 获取报警来源字典
  const alarmSource = await getAlarmSourceDict()
  alarmSourceList.value = alarmSource.data
})
/**
 * 获取报警类型字典
 * @param val 报警来源ID
 */
async function getAlarmTypeDictFun (val: string) {
  if (val) {
    // 如果选择了报警来源，获取对应的报警类型
    const res = await getAlarmTypeDict(val)
    alarmTypeList.value = res.data
    search.alarmType = ''
  } else {
    // 如果清空了报警来源，清空报警类型列表
    alarmTypeList.value = []
    search.alarmType = ''
  }
}

/**
 * 根据ID获取报警来源名称
 * @param id 报警来源ID
 * @returns 报警来源名称
 */
function getAlarmSource (id: string) {
  const res = alarmSourceList.value.find((item) => item.id === id)
  return res?.label
}

/**
 * 处理报警项点击事件，显示详情对话框
 * @param item 报警项
 */
function handleAlarmItem (item: AlarmItem) {
  let comp = null

  // 根据报警来源选择不同的详情组件
  if (item.alarmSource === '0') {
    // 矿数卫士
    comp = '恒值异常'
  } else if (item.alarmSource === '1') {
    // 监测监控
    comp = JcjkAlarmDetail
    item.id = item.alarmId
  } else if (item.alarmSource === '2') {
    comp = '风速异常'
  } else if (item.alarmSource === '3') {
    comp = '温度异常'
  }

  // 打开对话框显示详情
  $bDialog({
    title: `${item.areaName} · ${item.alarmTypeName}`,
    Comp: comp,
    CompParams: item,
    width: 800,
    height: 430
  })
}

const authStore = useAuthStore()
const { openDialog } = useDialog()

function goBackTrack(row) {
  $bDialog.closeAll()
  authStore.setGlobalParamsItem('startTime', dayjs(row.beginTime).subtract(0.5, 'hour').format('YYYY-MM-DD HH:mm:ss'))
  authStore.setGlobalParamsItem('endTime', dayjs(row.beginTime).add(0.5, 'hour').format('YYYY-MM-DD HH:mm:ss'))
  authStore.setGlobalParamsItem('alarmId', row.alarmId)
  authStore.setGlobalParamsItem('cdCode', row.cdCode)
  authStore.setGlobalParamsItem('areaId', row.areaId)
  authStore.setGlobalParamsItem('areaName', row.areaName)
  authStore.setModeParamsItem('model', 'backtracking')

  // openDialog(row.areaName, BBackTrack, row, {
  //   width: 800,
  //   height: 430,
  //   hideTools: true
  // })
}
</script>

<style lang="scss" scoped>
.alarm {
  display: flex;
  flex-direction: column;
  gap: 8px;
  height: 100%;

  .tools {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding-left: 16px;
  }

  .alarm-list {
    flex: 1;
    overflow-y: auto;
    padding-left: 16px;
    direction: rtl;

    .alarm-item {
      display: flex;
      flex-direction: column;
      margin-bottom: 8px;
      background: #0a302fad;
      padding: 8px;
      gap: 4px;
      cursor: pointer;
      direction: ltr;
      position: relative;

      &:last-child {
        margin-bottom: 0;
      }

      &.notRead::before {
        content: '';
        position: absolute;
        right: 8px;
        width: 4px;
        height: 4px;
        border-radius: 50%;
        background-color: var(--el-color-danger);
        box-shadow: 0 0 5px 2px var(--el-color-danger);
      }

      .alarm-item-track{
        position: absolute;
        cursor: pointer;
        top: 10px;
        right: 20px;
      }

      .alarm-item-alarm-type {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;

        .alarm-item-alarm-type-text {
          color: var(--el-color-primary);
        }
      }

      .alarm-item-time-duration {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12px;
        color: var(--text-color-placeholder);
        font-size: 12px;
      }

      .alarm-item-content {
        margin-top: 8px;
        color: var(--text-color-disabled);
        font-size: 12px;
      }
    }

    .status {
      text-align: center;
      padding: 8px 0;
      direction: ltr;
    }
  }
}
</style>
